
function tbl(){}
tbl_conf = {}
tbl_conf["funcs"] = {}

tbl_conf["pgSize"] = 10
tbl_conf["pgCurrent"] = 0
tbl_conf["pgCount"] = 0

tbl_conf["funcs"]["init"] = function(container_id,
	coldefs,row_actions,rows_action,tbl_class,global_name,ext_row,dataurl){
	if(!Handlebars) return
	this["dataUrl"] = dataurl

	this["containerID"] = container_id
	this["pgCount"] = 0
	this["pgCurrent"] = 1
	this["pgSize"] = 10
	this["rowActions"] = row_actions
	this["rowsActions"] = rows_actions
	this["colDefs"] = coldefs
	this["extRow"] = ext_row //扩展行

	// 查询和排序
	this["qseq"] = ""
	this["qverb"] = ""
	this["qpt"] = "" // query pattern
	this["odir"] = "" // 排序串
	this["oseq"] = 0
	this["start"] = 0  // limit
	var colnum = this["rowActions"]?1:0
	for(var col in coldefs){
		if(coldefs[col].visible) colnum ++
	}

	if(colnum==1) return
	this["colCount"] = colnum
	this["tblClass"] = tbl_class
	this["globalName"] = "_eachmaTBL_"+global_name
	this["tplMain"] = '<table class="{{tblClass}}">'+
	'<thead><tr><td colspan="{{colCount}}">'+
	' <select id="selColname"><option value="-1">所有</option>'+
	'{{#each colDefs}}{{#if retrievable}}'+
	'<option value="{{seq}}" id="selRCol">{{title}}</option>'+
	'{{/if}}{{/each}}</select><select id="selVerb"><option value="k">包含</option>'+
	'<option value="p">前缀</option><option value="s">后缀</option>'+
	'<option value="g">大于</option><option value="l">小于</option><option value="e">等于</option></select>'+
	'<input type="text" id="txtQuery" size="5"/>'+
	'<button id="btnRetrive" data-gn="{{globalName}}">查</button>'+
	'<select id="selSCol">{{#each colDefs}}{{#if sortable}}'+
	'<option value="-1"> </option><option  value="{{seq}}">{{title}}</option>'+
	'{{/if}}{{/each}}</select><select id="selDirection">'+
	'<option value="d">降序</option><option value="a">升序</option></select><button id="btnSort" '+
	' data-gn="{{globalName}}">排</button>'+
	'<td>{{#if extRow}}<button id="btnExtRow" data-show="n" title="实现/隐藏扩展行">'+
	'显示</button>{{/if}}<tr>'+
	'{{#each colDefs}}{{#if  visible}}<th>{{#if isID}}'+
	'<input id="checkAll" type="checkbox" />{{/if}}{{title}}'+
	'</th>{{/if}}{{/each}}{{#if rowActions}}<th>操作</th>{{/if}}<tr></thead>'+
	'<tbody></tbody><tfoot><tr><td colspan="{{colCount}}">'+
	'<button data-act="1" data-gn="{{globalName}}" class="pg">首页</button>'+
	'<button data-act="2" data-gn="{{globalName}}" class="pg">上一页</button>'+
	'<button data-act="3" data-gn="{{globalName}}" class="pg">下一页</button>'+
	'<button data-act="4" data-gn="{{globalName}}" class="pg">末页</button>'+
	'<button data-act="5" data-gn="{{globalName}}" class="pg">跳转</button>'+
	'<button data-act="6" data-gn="{{globalName}}" class="pg">设置</button>'+
	'<label id="pginfo"></label>&nbsp;&nbsp;'+
	'{{#each rowsActions}}<button data-gn="{{../globalName}}" '+
	'data-action="{{@index}}" class="rowsaction">{{title}}</button>'+
	'{{/each}}</td></tr></tfoot>'+
	'</table>'
	
	tblInit(this)
	window[this["globalName"]]  = this
}
tbl_conf["funcs"]["setDataUrl"] = function(url){
	this["dataUrl"] = url
}

tbl.prototype = tbl_conf
function tblInit(tbl){
	var tpl = Handlebars.compile(tbl["tplMain"])
	var theTbl = document.querySelector("#"+tbl["containerID"])
	theTbl.innerHTML = tpl(tbl)

	// 检索与排序
	var getQueryConf = function(){
		tbl["qseq"] = theTbl.querySelector("#selColname").value
		tbl["qverb"] = theTbl.querySelector("#selVerb").value
		tbl["qpt"] = theTbl.querySelector("#txtQuery").value.trim()
		tbl["odir"] = theTbl.querySelector("#selDirection").value
		tbl["oseq"] = theTbl.querySelector("#selSCol").value
	}
	_e.bind("#btnRetrive","click",function(){
		var tb = window[this.getAttribute("data-gn")]
		getQueryConf()
		tb.funcs.loadData.call(tb)
	},theTbl)

	_e.bind("#btnSort","click",function(){
		var tb = window[this.getAttribute("data-gn")]
		getQueryConf()
		tb.funcs.loadData.call(tb)
	},theTbl)

	var checkall = function(){
		var chinputs = theTbl.querySelectorAll(".check")
		for (var i=0; i<chinputs.length;i++){
			chinputs[i].checked  = this.checked

		}
	}
	_e.bind("#checkAll","click",checkall,theTbl)

	var pg = function(){
		var tbl = window[this.getAttribute("data-gn")]
		var action = parseInt(this.getAttribute("data-act"),10)
		var pgno = tbl["pgCurrent"]
		switch (action){
			case 1: pgno=1;break
			case 2: pgno--;break
			case 3: pgno++;break
			case 4: pgno=tbl["pgCount"];break
			case 5: pgno = parseInt(prompt("输入页码",10),10);break
			default:
				pgno = parseInt(prompt("输入显示记录条数",30),10)
				if(pgno>10) tbl["pgSize"] = pgno
				pgno = 1
		}

		if(pgno>0 && pgno<tb["pgCount"]+1){
			tbl["pgCurrent"] = pgno
			tbl.funcs.loadData.call(tb)
		}else{
			alert("不能翻页")
		}
		theTbl.querySelector("#pginfo").innerHTML = tb["pgCurrent"]+"/<b>"+tb["pgCount"]+"</b>"
	}
	_e.bindAll(".pg","click",pg,theTbl)


	// rowactions 预处理
	for(var k in tbl["rowActions"]){
		tbl["rowActions"][k]["supplement"] = '{{rowno}}'
	}
	var rowActionTpl =  '<div class="dropdown">'+
	'<button class="btn dropdown-toggle" type="button" id="dropdownMenu" data-toggle="dropdown">'+
	'操作<span class="caret"></span></button>'+
	'<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">'+
	'{{#each rowActions}}<li><a data-gn="{{../globalName}}"'+
	' class="{{cls}} rowact" data-funcno="{{@index}}" data-rowno="{{supplement}}">{{title}}</a></li>{{/each}}</ul></div>'
	/* '{{#each rowActions}}<button data-gn="{{../globalName}}"'+
	' class="{{cls}} rowact" data-funcno={{@index}} data-rowno="{{supplement}}">{{title}}</button>{{/each}}'
	*/
	tbl["genRowActions"] = Handlebars.compile((Handlebars.compile(rowActionTpl))(tbl))

	// 操作多行
	var rowsaction = function(){
		var tbl = window[this.getAttribute("data-gn")]
		var fn = tbl["rowsActions"][this.getAttribute("data-action")]

		var selRows = []
		var chinputs = theTbl.querySelectorAll(".check")
		for(var i=0; i<chinputs.length;i++){
			if(chinputs[i].checked){
				selRows.push(chinputs[i].getAttribute("data-val"))
			}
		}
		
		fn.func(tbl,selRows)
	}
	_e.bindAll(".rowsaction","click",rowsaction,theTbl)
	
	
	
	var showExt = function(){
		var flag = this.getAttribute("data-show")
		var trs = theTbl.querySelectorAll("tr.extrow")
		
		if(flag=='y') {
			
			for(var i=0; i<trs.length;i++){
				trs[i].style.display = "none"
			}
			
			
			this.setAttribute("data-show",'n')
			this.innerHTML = "显示"
		}else{
			for(var i=0; i<trs.length;i++){
				trs[i].style.display = "inline"
			}
			this.setAttribute("data-show",'y')
			this.innerHTML = "隐藏"
		}
	}
	_e.bind("#btnExtRow","click",showExt,theTbl)
	
}

tbl_conf["funcs"]["loadData"] = function(){
	var tbl = this
	var fd = new FormData(), xhr = new XMLHttpRequest()
	fd.append("pgsize", this["pgSize"])
	fd.append("start",(this["pgCurrent"]-1)*this["pgSize"])
	fd.append("qseq",this["qseq"]) // query column seq
	fd.append("qverb",this["qverb"]) //
	fd.append("qpt",this["qpt"]) // query pattern
	fd.append("oseq",this["oseq"]) //
	fd.append("odir",this["odir"])

	xhr.open("POST" ,tbl["dataUrl"] , true)
	xhr.send(fd)
	xhr.onreadystatechange=function()  {
		if (xhr.readyState==4 && xhr.status==200){

			var d = eval('('+xhr.responseText+');')
			tbl["data"] = d["rows"]
			tbl["data"].pop() // 删除最后一个空元素
			var c = d["count"]/tbl["pgSize"]
			tbl["pgCount"] = d["count"]%tbl["pgSize"]==0 ? c:Math.floor(c)+1
			tbl["funcs"]["genTBody"](tbl)
		}
	}
}

tbl_conf["funcs"]["genTBody"] = function(tbl){
	var theTbl = document.querySelector("#"+tbl["containerID"])
	
	tbodyStr = "",	colDefs = tbl["colDefs"],	rowActionStr = ""
	for(var i in tbl["data"]){
		var trStr = ""
		var tds = ""
		for(var k in colDefs){
			tds +="<td>"
			if(colDefs[k].isID){
				/*
				if (tbl["extRow"]){
					tds += '<button class="expand" data-rowno="'+i+'">+</button>'
				}*/
				tds += '<input type="checkbox" class="check" '+
				'data-val="'	+ i+'" />'
			}
			if(colDefs[k].render){
				tds +=
				colDefs[k].render(tbl["data"][i][colDefs[k].seq])
			}else{
				tds +=""+tbl["data"][i][colDefs[k].seq]
			}
			tds += "</td>"
		}
		// 补上row_actions，前面预定义好模板了。
		trStr += tds+"<td>"+tbl["genRowActions"]({"rowno":i})+"</td>"
		tbodyStr += "<tr>"+trStr+"</tr>"

		// 也许还有扩展行
		if(tbl["extRow"]){
			tbodyStr += '<tr class="extrow"><td colspan="' +tbl["colCount"]+'">'+
			tbl["extRow"](tbl["data"],i)+'</td></tr>'
		}
	}
	theTbl.querySelector("tbody").innerHTML = tbodyStr
	// 绑单行事件
	var rowact = function(){
		var funcno = this.getAttribute("data-funcno")
		,tbl = window[this.getAttribute("data-gn")]
		,rowno = this.getAttribute("data-rowno")
		tbl["rowActions"][funcno].func(tbl,rowno)



	}
	_e.bindAll(".rowact","click",rowact,theTbl)

	// 显示、隐藏扩展行
	var ch = theTbl.querySelector("#btnExtRow").getAttribute("data-show")
	if(ch=='n'){
		var trs = theTbl.querySelectorAll("tr.extrow")
		for(var i=0; i<trs.length;i++){
			trs[i].style.display = "none"
		}
		
	}
	
	

}
